﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Text;
using System.Threading;
using System.Windows.Forms;
using DevExpress.Xpo;
using DevExpress.XtraEditors;
using NetworkSupervisor.Helper;
using NetworkSupervisor.Model.NetworkSupervisor;
using System.Linq;

namespace NetworkSupervisor
{
    public partial class FormQQOnLineCheck : DevExpress.XtraEditors.XtraForm
    {
        private bool stopIt;

        /// <summary>
        /// 时间间隔，以分钟为单位
        /// </summary>
        private int timeSpan;

        public FormQQOnLineCheck()
        {
            InitializeComponent();
        }

        private void btnStart_Click(object sender, EventArgs e)
        {
            string text = txtSpan.Text;
            if (text == "")
            {
                XtraMessageBox.Show("请输入时间间隔");
                return;
            }

            btnStart.Enabled = false;
            btnStop.Enabled = true;
            timeSpan = Convert.ToInt32(text);
            txtSpan.Enabled = false;
            stopIt = false;
            dataGridView1.Rows.Clear();
            System.Threading.ThreadPool.QueueUserWorkItem(callBack);
        }

        private void callBack(object state)
        {
            int onLineCount = 0;
            this.UIThread(() => dataGridView1.Rows.Clear());
            int rowCount = gridView1.RowCount;
            for (int i = 0; i < rowCount; i++)
            {
                taQQ列表 item = gridView1.GetRow(i) as taQQ列表;
                bool onLine = false;
                try
                {
                    onLine = QQHelper.CheckQQOnLine(item.QQ);
                }
                catch
                {
                }
                this.UIThread(() =>
                                  {
                                      item.是否在线 = onLine;
                                      item.Save();
                                  });
                this.UIThread(() => gridView1.FocusedRowHandle = i);
                this.UIThread(() => progressBarControl1.Position = (int) ((double) (i + 1)*1000/(double) rowCount));

                DateTime dateTime = DateTime.Now;
                this.UIThread(() =>
                                  {
                                      taQQ在线纪录 item2 = new taQQ在线纪录(session1);
                                      item2.QQ = item.QQ;
                                      item2.在线时间 = dateTime;
                                      item2.在线状态 = onLine ? 1 : 0;
                                      item2.Save();
                                  });

                if (onLine)
                {
                    onLineCount++;
                    this.UIThread(() => dataGridView1.Rows.Add(new string[] {onLineCount.ToString(), item.单位, item.姓名, item.QQ}));
                    this.UIThread(() => item.Set上次在线时间());
                    this.UIThread(() => item.Set在线次数());
                }

                if (stopIt)
                {
                    return;
                }
            }
            this.UIThread(() =>
                              {
                                  timer1.Interval = timeSpan*60*1000;
                                  timer1.Start();
                              });
        }

        private void FormQQOnLineCheck_Load(object sender, EventArgs e)
        {
            Control.CheckForIllegalCrossThreadCalls = false;

            btnStart.Enabled = true;
            btnStop.Enabled = false;
            stopIt = false;
        }

        private void gridView1_DoubleClick(object sender, EventArgs e)
        {
            if (gridView1.RowCount < 1) return;
            string qqCode = gridView1.GetFocusedRowCellDisplayText("QQ");
            string url = QQHelper.GetQQOnlineChatUrl(qqCode);
            System.Diagnostics.Process.Start(url);
        }

        private void FormQQOnLineCheck_Resize(object sender, EventArgs e)
        {
            groupControl2.Width = this.Width/2 + 100;
        }

        private void dataGridView1_DoubleClick(object sender, EventArgs e)
        {
            if (dataGridView1.RowCount < 1) return;
            string qqCode = dataGridView1.SelectedRows[0].Cells[2].Value.ToString();
            string url = QQHelper.GetQQOnlineChatUrl(qqCode);
            System.Diagnostics.Process.Start(url);
        }

        private FormLoadProgress formLoadProgress = null;

        private void FormQQOnLineCheck_Shown(object sender, EventArgs e)
        {
            btnStart.Enabled = false;
            formLoadProgress = new FormLoadProgress();
            formLoadProgress.mySetInfo("正在加载数据，请等候...");
            formLoadProgress.mySetProgressPosition(0);
            formLoadProgress.mySetProgressMaximum(XPCQQ列表.Count);
            System.Threading.ThreadPool.QueueUserWorkItem(initOnlineCountAndLastOnLineTime);
        }

        private void initOnlineCountAndLastOnLineTime(object state)
        {
            //关键，使用BeginInvoke，无需等待ShowDialog返回，继续往下执行
            this.UIThreadBeginInvoke(() => formLoadProgress.ShowDialog());
            int count = XPCQQ列表.Count;
            int onLineCount = 0;
            for (int i = 0; i < count; i++)
            {
                taQQ列表 item = XPCQQ列表[i] as taQQ列表;
                this.UIThread(() => item.Set在线次数());
                if (item.在线次数 > 0) this.UIThread(() => item.Set上次在线时间());
                this.UIThread(() => formLoadProgress.mySetProgressPosition(i + 1));
                //   this.UIThreadBeginInvoke(() => gridView1.FocusedRowHandle = i);
                if (item.是否在线)
                {
                    onLineCount++;
                    this.UIThreadBeginInvoke(() => dataGridView1.Rows.Add(new string[] {onLineCount.ToString(), item.单位, item.姓名, item.QQ}));
                    //      this.UIThreadBeginInvoke(() => dataGridView1.CurrentCell = dataGridView1.Rows[onLineCount - 1].Cells[0]);
                }
            }
            this.UIThread(() => btnStart.Enabled = true);
            this.UIThread(() => formLoadProgress.myClose());
        }

        private void FormQQOnLineCheck_FormClosing(object sender, FormClosingEventArgs e)
        {
            stopIt = true;
        }

        private void btnExport_Click(object sender, EventArgs e)
        {
            SaveFileDialog f = new SaveFileDialog();
            f.Filter = "Excel(*.xls)|*.xls";
            f.FileName = "在线情况统计列表" + DateTime.Now.ToString("yyyy年MM月dd日") + ".xls";
            if (f.ShowDialog() == DialogResult.OK)
            {
                gridControl1.ExportToXls(f.FileName);
                if (XtraMessageBox.Show("导出成功，是否打开？", "", MessageBoxButtons.OKCancel, MessageBoxIcon.Question) == DialogResult.OK)
                {
                    System.Diagnostics.Process.Start(f.FileName);
                }
            }
        }

        private void btnStop_Click(object sender, EventArgs e)
        {
            if (XtraMessageBox.Show("正在监控QQ，是否确认退出监控？", "", MessageBoxButtons.OKCancel, MessageBoxIcon.Question) != DialogResult.OK)
            {
                return;
            }

            btnStart.Enabled = true;
            btnStop.Enabled = false;
            txtSpan.Enabled = true;
            stopIt = true;
            progressBarControl1.Position = progressBarControl1.Properties.Maximum;
            timer1.Stop();
        }

        private void textEdit1_KeyPress(object sender, KeyPressEventArgs e)
        {
            if (!char.IsNumber(e.KeyChar)) e.Handled = true;
        }

        private void timer1_Tick(object sender, EventArgs e)
        {
            System.Threading.ThreadPool.QueueUserWorkItem(callBack);
            timer1.Stop();
        }

        private void gridView1_CustomDrawRowIndicator(object sender, DevExpress.XtraGrid.Views.Grid.RowIndicatorCustomDrawEventArgs e)
        {
            if (e.Info.IsRowIndicator)
            {
                e.Info.DisplayText = (e.RowHandle + 1).ToString();
            }
        }
    }
}